/* eslint-disable */
const fs = require('fs');
const fsPromises = require('fs').promises;
const { LANG_CODE_REG } = require('./consts');
const { getDataFromTsv } = require('./tsv2json');

const IS_MUI = false;
const parseCofig = (() => {
  if (IS_MUI) {
    return {
      KEY_QUOTE: '', // kc/mui '', 
      IS_MUI: true,
    }
  }
  return {
    KEY_QUOTE: '"', //
    IS_MUI: false,
  }
})()

const formatKey = (key) => {
  if (parseCofig.IS_MUI) {
    return key.split('.').join('_');
  }
  return key;
}
// 这个可能需要读取一个文件夹的数据；
const default_langs = ["zh_CN","en_US","zh_HK","vi_VN","tr_TR","ru_RU","pt_PT","nl_NL","ko_KR","ja_JP","it_IT","fr_FR","es_ES","de_DE"]; //eslint-disable-line

const replaceAt = (str, start, end, replacement) => {
  return str.slice(0, start) + replacement + str.slice(end);
}
const replaceValue = (str, keyval, valStr, replacement) => { // matches[3]
  const start = str.indexOf(keyval);
  const valueStart = str.indexOf(valStr, start);
  const end = valueStart + valStr.length;
  return replaceAt(str, valueStart, end, replacement);
  
}
const getDataByJson = (jsonstr) => {
  const result = [];
  // 多行模式 /^ *["']?([\w.]+)["']?\s*:\s*(["'](.+)["'] *)(?=(?:,? *$))/m;
  // / *["']?([\w.]+)["']?\s*:\s*(["'](.+)["'] *)(?=(?:,? *\r?\n))/;
  const reg = /( *["']?([\w.]+)["']?\s*:\s*)(["'](.+)["'] *)(?=(?:, *\r?\n|\n *}))/g;
  let matches;
  while ((matches = reg.exec(jsonstr)) !== null) {
    // result.push([matches[1], matches[3]]);
    result.push({
      index: matches.index,
      matched: matches[0],
      key: matches[2],
      value: matches[4],
      valStartIndex: matches.index + matches[1].length,
      lastIndex: reg.lastIndex,
      valStr: matches[3],
      quote: matches[3].slice(0, 1) === "'" ? "'" : '"' 
    })
  }
  return result;
};

async function addFromTsv(commandArgs) {
  const directory = commandArgs[0];
  let files = await fsPromises.readdir(`source/${directory}`);
  const languages = [];
  files = files.filter((name) => {
    const matches = name.match(LANG_CODE_REG);
    if (matches) {
      languages.push(matches[0]);
      return true;
    }
    return false;
  });
  // 按照默认的语言顺序排序
  // languages.sort((a, b) => {
  //   let val1 = default_langs.indexOf(a);
  //   let val2 = default_langs.indexOf(b);
  //   val1 = val1 < 0 ? val1 = 100 : val1;
  //   val2 = val2 < 0 ? val2 = 100 : val2;
  //   return val1 - val2;
  // });
  // 读取tsv文件数据
  const tsvStr = await fsPromises.readFile(`source/${commandArgs[1]}`, { encoding: 'utf8' });
  // 读取files的数据
  const langData = {};
  const needUpdateData = getDataFromTsv(tsvStr);
  for (const filename of files) {
    let fileStr = await fsPromises.readFile(`source/${directory}/${filename}`, { encoding: 'utf8' });
    const originData = getDataByJson(fileStr);
    const lang = filename.match(LANG_CODE_REG)[0];
    langData[lang] = originData;
    const updateData = needUpdateData.find(item => item.lang === lang);
    if (updateData) {
      let needAddStr = '';
      for (let [updateKey, updateVal] of updateData.trans) {
        // 如果以前已经存在这个key
        const finded = originData.find((item) => item.key === formatKey(updateKey));
        if (finded) {
          // 替换这个key的value
          fileStr = replaceValue(
            fileStr,
            finded.matched,
            finded.valStr,
            `${finded.quote}${updateVal}${finded.quote}`,
          )
        } else {
          // 如果没有在最后一行添加这个key, value
          needAddStr += `  ${parseCofig.KEY_QUOTE}${formatKey(updateKey)}${parseCofig.KEY_QUOTE}: ${JSON.stringify(updateVal)},\n`;
        }
      }
      if (needAddStr) {
        const endstr = fileStr.match(/}\)?;?\s?$/)[0];
        fileStr = fileStr.replace(/}\)?;?\s?$/, needAddStr);
        fileStr += endstr;
      }
      await fsPromises.writeFile(`output/${directory}/${filename}`, fileStr);
    }
  }
}

module.exports.default = addFromTsv;
module.exports.getDataByStr = getDataByJson;
